package ua.soso.ui.mvc;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import ua.soso.dao.model.User;
import ua.soso.service.FileService;
import ua.soso.service.UserService;
import ua.soso.service.bean.FileBean;
import ua.soso.service.bean.FileCategoryBean;
import ua.soso.service.bean.UserBean;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class MainController {
    private FileService fileService;
    private UserService userService;

    @Required
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }

    @Required
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/files.html", method = RequestMethod.POST)
    public ModelAndView login(@ModelAttribute("user")
                              User user, BindingResult result, HttpSession session) {
        UserBean userBean = userService.getUser(user.getLogin(), user.getPassword());

        if (userBean != null) {
            session.setAttribute("logged", userBean);

            return getFilesPage();
        }

        return new ModelAndView("home", "command", new User());
    }

    @RequestMapping(value = "/files.html", method = RequestMethod.GET)
    public ModelAndView hackLogin() {
        return new ModelAndView("home", "command", new User());
    }

    @RequestMapping(value = "/home.html", method = RequestMethod.GET)
    public ModelAndView getHomePage(HttpSession session) {
        if (session.getAttribute("logged") != null) {
            return getFilesPage();
        }

        return new ModelAndView("home", "command", new User());
    }

    @RequestMapping(value = "/logout.html", method = RequestMethod.GET)
    public ModelAndView logout(HttpSession session) {
        session.removeAttribute("logged");

        return new ModelAndView("home", "command", new User());
    }

    private ModelAndView getFilesPage() {
        ModelAndView modelAndView = new ModelAndView("files");

        List<FileCategoryBean> categories = fileService.getCategories();

        modelAndView.addObject("categoryList", categories);

        return modelAndView;
    }
}
